<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think;

class Page
{

    private $totalPages;

    public $nowPage;

    public $firstRow;

    public $listRows;

    public function __construct($count,$rows){

        $this->totalPages = ceil($count/$rows);

        $_GET["page"] = isset($_GET["page"]) ? intval($_GET["page"]) : 1;

        $_GET["page"] = intval($_GET["page"]) > 0 ? intval($_GET["page"]) : 1;

        // if ($_GET["page"] > 1) {
        //     if ($_GET["page"] > $this->totalPages) {
        //         $_GET["page"] = $this->totalPages;
        //     }
        // }else{
        //     $_GET["page"] = 1;
        // }

        $this->nowPage = intval($_GET["page"]);

        $this->firstRow = ($this->nowPage - 1) * $rows;
        $this->listRows = $rows;
    }

    public function pageUrl(){

        if (strpos($_SERVER ["REQUEST_URI"],'?') !== false) {
            $exp = explode("?",$_SERVER ["REQUEST_URI"]);
            $str = $exp[1];
            $url = $exp[0];
            parse_str($str,$parse);
            unset($parse["page"]);
            $str = http_build_query($parse);
        }else{
            $url = $_SERVER ["REQUEST_URI"];
        }

        if (!empty($str)) {
            return $url."?".$str."&page=";
        }else{
            return $url."?page=";
        }
    }

    public function show(){
        $page = '<div>';
        $nowPage = $this->nowPage;
        $totalPages = $this->totalPages;
        $url = $this->pageUrl();
        if ($nowPage > 1) {
            $prev = $nowPage - 1 > $totalPages ? $totalPages : $nowPage - 1;
           
            $page .= '<a class="prev" href="'.$url.$prev.'"><<</a>';
        }

        $start = intval(($nowPage - 1) / 10) * 10 + 1;
        $end = ($start + 9) > $totalPages ? $totalPages : $start + 9 ;

        for ($i=$start; $i <= $end; $i++) { 
            if ($i == $nowPage) {
                $page .= '<span class="current">'.$i.'</span>';
            }else{
                $page .= '<a class="num" href="'.$url.$i.'">'.$i.'</a>';
            }
        }

        if ($nowPage < $totalPages) {
            $nowPage++;
            $page .= '<a class="next" href="'.$url.$nowPage.'">&gt;&gt;</a>';
        }

        $page .= '</div>';
        return $page;

    }
}
